package eerbaar.internal.elements.extension;

import java.util.ArrayList;
import java.util.List;

import eerbaar.elements.extension.ILeaderElement;
import eerbaar.elements.extension.ILeaderListener;
import eerbaar.elements.extension.IPackMemberElement;
import eerbaar.extension.IExtensible;

public class LeaderElementImpl implements ILeaderElement {

    private final IExtensible parent;
    private final List<IExtensible> members = new ArrayList<IExtensible>();
    private final List<ILeaderListener> listeners = new ArrayList<ILeaderListener>();

    public LeaderElementImpl(IExtensible parent) {
        this.parent = parent;
    }

    @Override
    public boolean add(IPackMemberElement member) {
        if (!this.members.contains(member)) {
            this.members.add(member);
            member.setLeader(this);
            fireMemberAdded(member);
            return true;
        }
        return false;
    }

    @Override
    public void addListener(ILeaderListener listener) {
        if (!this.listeners.contains(listener)) {
            this.listeners.add(listener);
        }
    }

    @Override
    public IExtensible copy() {
        return new LeaderElementImpl(this.parent);
    }

    private void fireMemberAdded(IPackMemberElement member) {
        for (ILeaderListener l : this.listeners) {
            l.onMemberAdded(member);
        }
    }

    private void fireMemberRemove(IPackMemberElement member) {
        for (ILeaderListener l : this.listeners) {
            l.onMemberRemove(member);
        }
    }

    @Override
    public <T extends IExtensible> T getExtension(Class<T> type) {
        return this.parent.getExtension(type);
    }

    @Override
    public int getMemberCount() {
        return this.members.size();
    }

    @Override
    public void remove(IPackMemberElement member) {
        if (this.members.contains(member)) {
            this.members.remove(member);
            member.setLeader(null);
            fireMemberRemove(member);
        }
    }

    @Override
    public void removeListener(ILeaderListener listener) {
        if (this.listeners.contains(listener)) {
            this.listeners.remove(listener);
        }
    }
}
